// 云函数入口文件
//通过云函数调取数据库中博客内容
const cloud = require('wx-server-sdk')

cloud.init()

const TcbRouter = require('tcb-router')

const db = cloud.database()

const blogCollection =  db.collection('blog')// 博客集合

// 云函数入口函数
exports.main = async (event, context) => {
 const app = new TcbRouter({
   event
 })

 app.router('list', async(ctx,next)=>{
  const keyword = event.keyword
  let w = {}
  if (keyword.trim() !=  '') {
    w = {
      content: db.RegExp({
        regexp: keyword,
        options: 'i'
      })
    }
  }

   let blogList = await blogCollection.where(w).skip(event.start).limit(event.count)
   .orderBy('createTime','desc').get().then((res)=>{
     return res.data
   })            //分页查询
   ctx.body = blogList

 })


 app.router('detail', async (ctx, next) => {
  let blogId = event.blogId


  // 聚合查询
  const blog = await blogCollection.aggregate().match({
    _id: blogId
  }).lookup({
    from: 'blog-comment',
    localField: '_id',
    foreignField: 'blogId',
    as: 'commentList'
  }).end()
  ctx.body = blog
})

const wxContext = cloud.getWXContext()
app.router('getListByOpenid', async (ctx, next) => {
  ctx.body = await blogCollection.where({
      _openid: wxContext.OPENID
    }).skip(event.start).limit(event.count)
    .orderBy('createTime', 'desc').get().then((res) => {
      return res.data
    })
})





return app.serve()
}